﻿using HslCommunication.MQTT;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataCapture.Helper
{
    class MQTTConsoleClient
    {
        //通过 Lazy<T>，实现了一个线程安全的单例模式。因为 Lazy<T> 的 Value 属性是线程安全的。
        private static readonly Lazy<MQTTConsoleClient> instance = new Lazy<MQTTConsoleClient>(() => new MQTTConsoleClient());
        public static MQTTConsoleClient Instance => instance.Value;


        private MqttClient mqttClient;

        
        public MQTTConsoleClient()
        {
            mqttClient = new MqttClient(new MqttConnectionOptions()
            {
                ClientId = "ReadClient",                                   // 客户端的唯一的ID信息
                IpAddress = "127.0.0.1",                                   // 服务器的地址
                Credentials = new MqttCredential("admin", "123456")        // 设置了用户名和密码
            });

            HslCommunication.OperateResult connect = mqttClient.ConnectServer();
            if (connect.IsSuccess)
            {
                if (MainForm.Instance != null)
                {
                    Log4NetHelper.Debug("MQTT客户器连接服务器成功");
                }
            }
            else
            {
                if (MainForm.Instance != null)
                {
                    Log4NetHelper.Debug("MQTT客户器连接服务器失败");
                }
            }
        }

        /// <summary>
        /// MQTT消息发送：客户端向服务端发送消息
        /// </summary>
        /// <param name="deviceData">数据源</param>
        /// <param name="Topic">主题</param>
        public  void ClientForServerData<T>(T deviceData, string Topic)
        {
            try
            {
                JObject json = new JObject();
                json.Merge(JObject.FromObject(deviceData));

                // 发布示例
                HslCommunication.OperateResult connect = mqttClient.PublishMessage(new MqttApplicationMessage()
                {
                    Topic = Topic,                                                           // 主题
                    QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,          // 如果是实时数据，适合用这个
                    Payload = Encoding.UTF8.GetBytes(json.ToString())                      // 发布的数据
                });
                if (connect.IsSuccess)
                {
                    // 发布成功
                }
                else
                {
                    // 发布失败
                }
            }
            catch (Exception ex)
            {
               //报错
            }
        }
    }
}
